﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Security.Cryptography;

namespace QD.Utils
{
    public class IOUtils
    {
        public static void CreateDirectoryIfNotExists(string dirPath)
        {
            try
            {
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
            }
            catch
            {
            }
        }

        public static bool CreateFile(string filePath, Stream stream)
        {
            try
            {
                stream.Seek(0L, SeekOrigin.Begin);
                CreateDirectoryIfNotExists(Path.GetDirectoryName(filePath));
                FileStream stream2 = new FileStream(filePath, FileMode.Create);
                byte[] buffer = new byte[0x2800];
                long length = stream.Length;
                while (length != 0L)
                {
                    int count = (length > 0x2800L) ? 0x2800 : ((int)length);
                    stream.Read(buffer, 0, count);
                    length -= count;
                    stream2.Write(buffer, 0, count);
                }
                stream2.Dispose();
                stream2.Close();
                stream.Dispose();
                stream.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool CreateFile(string filePath, string content)
        {
            try
            {
                FileStream stream = new FileStream(filePath, FileMode.Create);
                StreamWriter writer = new StreamWriter(stream, Encoding.GetEncoding("GB2312"));
                writer.Write(content);
                writer.Flush();
                writer.Close();
                stream.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool DownloadFile(HttpResponse Response, string filePath, string outputFileName, bool responseEnd, bool clearCache)
        {
            try
            {
                Response.ClearContent();
                switch (Path.GetExtension(outputFileName).ToLower())
                {
                    case ".swf":
                    case ".flv":
                        Response.ContentType = "application/x-shockwave-flash";
                        break;

                    case ".rmvb":
                    case ".rm":
                        Response.ContentType = "audio/x-pn-realaudio";
                        break;

                    case ".mp3":
                    case ".mpeg":
                    case ".mpg":
                        Response.ContentType = "audio/mpeg";
                        break;

                    case ".wav":
                        Response.ContentType = "audio/x-wav";
                        break;

                    case ".ra":
                        Response.ContentType = "audio/x-realaudio";
                        break;

                    case ".avi":
                        Response.ContentType = "video/x-msvideo";
                        break;

                    case ".mov":
                        Response.ContentType = "video/quicktime";
                        break;

                    default:
                        Response.ContentType = "application/octet-stream";
                        break;
                }
                if (!string.IsNullOrEmpty(outputFileName))
                {
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Encoding.GetEncoding(0xfde9).GetBytes(outputFileName)));
                }
                Response.TransmitFile(filePath);
                if (clearCache)
                {
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.Cache.SetNoStore();
                }
                if (responseEnd)
                {
                    Response.End();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }

        public static string GetFileMD5Code(Stream stream)
        {
            MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
            return BitConverter.ToString(provider.ComputeHash(stream)).Replace("-", "");
        }
        public static List<FileInfo> GetFiles(string path, string fileExtensions, SearchOption searchOption)
        {
            if (!Directory.Exists(path))
            {
                return new List<FileInfo>();
            }
            FileInfo[] files = new DirectoryInfo(path).GetFiles("*", searchOption);
            List<FileInfo> list = new List<FileInfo>();
            if (string.IsNullOrEmpty(fileExtensions))
            {
                foreach (FileInfo info2 in files)
                {
                    list.Add(info2);
                }
                return list;
            }
            string[] source = fileExtensions.Split(new char[] { '|' });
            foreach (FileInfo info2 in files)
            {
                if (source.Contains<string>(info2.Extension.ToLower()))
                {
                    list.Add(info2);
                }
            }
            return list;
        }
        public static List<FileInfo> GetImagFiles(string path, SearchOption searchOption)
        {
            return GetFiles(path, ".gif|.jpg|.jpeg|.bmp|.png", searchOption);
        }
        public static bool IfModified(DateTime lastModified, HttpContext context)
        {
            try
            {
                if ((context.Request.Headers["If-Modified-Since"] != null) && (DateTime.Parse(context.Request.Headers["If-Modified-Since"].Split(new char[] { ';' })[0]) > lastModified.AddSeconds(-1.0)))
                {
                    context.Response.StatusCode = 0x130;
                    context.Response.StatusDescription = "Not Modified";
                    return false;
                }
            }
            catch
            {
            }
            return true;
        }
        public static bool MoveFile(string orginFilePath, string targetFilePath)
        {
            try
            {
                if (File.Exists(orginFilePath))
                {
                    if (File.Exists(targetFilePath))
                    {
                        File.Delete(targetFilePath);
                    }
                    CreateDirectoryIfNotExists(Path.GetDirectoryName(targetFilePath));
                    File.Move(orginFilePath, targetFilePath);
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
        public static string ReadFirstLine(string file, Encoding encoding)
        {
            using (StreamReader reader = new StreamReader(file, encoding))
            {
                return reader.ReadLine();
            }
        }

        public static string GetFileExtName(string fileName)
        {
            if (string.IsNullOrEmpty(fileName) || (fileName.IndexOf('.') <= 0))
            {
                return string.Empty;
            }
            fileName = fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));
            return fileName.ToLower().Trim();
        }

        
    }
}